<?php

require_once 'CObject.php';

class CEncoder extends CObject {
	var $AllowLoss;
	
	function Init($allowLoss = null) {
		$this->AllowLoss = ($allowLoss == true); // may be null
	}
	
	function AppendChar($x) {
		CAbstract('CEncoder::AppendChar()', $this);
	}
	
	function AsBuffer() {
		CAbstract('CEncoder::AsBuffer()', $this);
	}
	
	function AppendString($s) {
		$allChars = &$s->AllCharacters();
		
		while (!is_null($c = $allChars->NextChar())) {
			$this->AppendChar($c);
		}
	}
	
	function __toString() {
		return $this->AsBuffer();
	}
}

class CBufferEncoder extends CEncoder {
	var $Buffer = '';
	var $_AllowFastMethods = true;
	
	function AppendChar($x) {
		$b = $this->BytesForChar($x);
		
		if (is_null($b)) {
			if ($this->AllowLoss)
				$this->Buffer .= $this->ReplacementBytes();
			else
				trigger_error("Cannot encode character U+".sprintf("%04X", $x)." with an encoder of class " . get_class($this) . ".", E_USER_ERROR);
			return;
		}
		
		$this->Buffer .= $b;
	}
	
	function AsBuffer() { return $this->Buffer; }
	
	function BytesForChar($x) {
		CAbstract('CBufferEncoder::BytesForChar()', $this);
	}
	
	function ReplacementBytes() {
		CAbstract('CBufferEncoder::ReplacementCharacter()', $this);
	}
	
	function FastAppendBuffer($buffer) {
		if (!$this->_AllowFastMethods) return false;
		$this->Buffer .= $buffer;
		return true;
	}
	
	function FastAppendIfEncoding($x, $encoding) {
		if (!$this->_AllowFastMethods) return false;
		$b = $x->FastBufferOfEncoding($encoding);
		if (is_null($b))
			return false;
		
		$this->Buffer .= $b;
		return true;
	}
}

?>